<template>
  <div>
    <!--条件搜索区域-->
    <el-row>
      <el-col :span="24">
        <el-card header=" ">
          <span class="header2">用户列表</span>
          <el-form :inline="true" style="text-align: center;">
            <el-form-item label="用户名称：">
              <el-input
                  v-model="searchuser.userName"
                  placeholder="请输入用户名"
                  clearable>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="search">
                <el-icon>
                  <Search/>
                </el-icon>&nbsp;&nbsp;搜索
              </el-button>
            </el-form-item>
            <el-form-item>
              <el-button @click="exportExcel">
                <el-icon>
                  <Bottom/>
                </el-icon>&nbsp;&nbsp;导出Excel
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!--数据显示区域-->
    <el-row>
      <el-col :span="24">
        <el-card>
          <!-- 新增按钮 -->
          <el-header style="background-color: #ffffff; margin-left: -5px">
            <el-button @click="handleSave()">
              <el-icon>
                <Plus/>
              </el-icon>&nbsp;&nbsp;新增用户
            </el-button>
          </el-header>
          <!-- 用户详细信息 -->
          <el-table :data="userData" style="width: 100%">
            <el-table-column
                width="80"
                prop="id"
                label="ID">
            </el-table-column>
            <el-table-column
                width="220"
                prop="name"
                label="用户名称">
            </el-table-column>
            <el-table-column
                width="140"
                prop="age"
                label="年龄">
            </el-table-column>
            <el-table-column
                width="120"
                prop="gender"
                label="性别">
            </el-table-column>
            <el-table-column
                prop="address"
                label="家庭地址">
            </el-table-column>
            <el-table-column
                prop="updateTime"
                label="更新时间">
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                    style="margin: 0 0 0 0"
                    type="warning"
                    @click="setDialog(scope.row.id,scope.row.name,scope.row.age,scope.row.gender,scope.row.address)"
                    slot="reference">
                  <el-icon>
                    <Setting/>
                  </el-icon>&nbsp;&nbsp;编辑
                </el-button>
                <el-popconfirm :title="('确定删除 '+ scope.row.name +' 吗？')" @confirm="remove(scope.row.name)">
                  <el-button
                      style="margin: 0 0 0 15px"
                      icon="el-icon-close"
                      type="danger"
                      slot="reference">删除
                  </el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!--分页-->
    <el-row class="page-row">
      <el-config-provider :locale="zhCn">
        <el-pagination
            class="el-pagination"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[5, 10, 30, 50, 200]"
            @size-change="sizeChange"
            @current-change="currentChange"
            @prev-click="currentChange"
            @next-click="currentChange"
            :current-page="current"
            :page-size="size"
            :total="total">
        </el-pagination>
      </el-config-provider>
    </el-row>

    <!-- 添加 -->
    <el-dialog title="添加用户" v-model="saveDialog" width="600px">
      <el-form :model="userObj" ref="ruleForm" label-width="80px">
        <el-form-item label="用户名称" prop="name" :rules="[{ required: true, message: '名称不能为空'}]">
          <el-input v-model="userObj.name" maxlength="8" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age" :rules="[{ type: 'number', required: true, message: '年龄必须为数字值'}]">
          <el-input v-model.number="userObj.age"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userObj.gender">
            <el-radio-button label="男"></el-radio-button>
            <el-radio-button label="女"></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="家庭地址" prop="address">
          <el-input v-model="userObj.address" show-word-limit></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 255px; margin: 45px 0 0 65px" @click="userAdd"
                     :disabled="userObj.name===''||userObj.age===null||typeof userObj.age !== 'number'"
          >立即添加
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog title="编辑用户" v-model="updateDialog" width="600px">
      <el-form :model="userSet" ref="ruleForm" label-width="80px">
        <el-form-item label="用户ID" prop="id">
          <el-input v-model="userSet.id" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="name" :rules="[{ required: true, message: '名称不能为空'}]">
          <el-input v-model="userSet.name" maxlength="8" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age" :rules="[{ type: 'number', required: true, message: '年龄必须为数字值'}]">
          <el-input v-model.number="userSet.age"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userSet.gender">
            <el-radio-button label="男"></el-radio-button>
            <el-radio-button label="女"></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="家庭地址" prop="address">
          <el-input v-model="userSet.address" show-word-limit></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 255px; margin: 45px 0 0 65px" @click="updateuser"
                     :disabled="userSet.name===''||userSet.age===null||typeof userSet.age !== 'number'"
          >确定修改
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {ref, onMounted} from 'vue';
import userApi from '@/assets/api/userApi';
import {ElMessage} from 'element-plus';
import {Bottom, Plus, Setting} from "@element-plus/icons-vue";

import { ElConfigProvider } from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn';

// 定义响应式数据
const adminName = ref('');
const searchuser = ref({userName: ''});
const userData = ref<any[]>([]);
const size = ref(5);
const current = ref(1);
const total = ref(0);
const saveDialog = ref(false);
const userObj = ref({
  name: '',
  age: null,
  gender: '男',
  address: ''
});
const updateDialog = ref(false);
const userSet = ref({
  id: null,
  name: '',
  age: null,
  gender: '男',
  address: ''
});

// 获取数据
const getData = async () => {
  try {
    const response = await userApi.getUserList({
      name: searchuser.value.userName,
      current: current.value,
      size: size.value
    });
    userData.value = response.data.data.userPage.records;
    total.value = response.data.data.userPage.total;
  } catch (error) {
    console.error('无法获取数据:', error);
  }
};

// 生命周期钩子，相当于Vue2的created
onMounted(() => {
  getData();
});

// 方法定义
const handleSave = () => {
  saveDialog.value = true;
};

function setDialog(id: null, name: string, age: null, gender: string, address: string) {
  userSet.value.id = id;
  userSet.value.name = name;
  userSet.value.age = age;
  userSet.value.gender = gender;
  userSet.value.address = address;
  updateDialog.value = true;
};

const remove = async (name: string) => {
  try {
    const response = await userApi.deleteUser({name});
    if (response.data.code === 200) {
      ElMessage.success(response.data.message);
      getData();
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    console.error('无法删除:', error);
  }
};

const userAdd = async () => {
  try {
    const response = await userApi.addUser({
      name: userObj.value.name,
      age: userObj.value.age,
      gender: userObj.value.gender,
      address: userObj.value.address
    });
    if (response.data.code === 200) {
      ElMessage.success(response.data.message);
      saveDialog.value = false;
      getData();
      userObj.value = {
        name: '',
        age: null,
        gender: '男',
        address: ''
      };
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    console.error('无法添加用户:', error);
  }
};

const updateuser = async () => {
  try {
    const response = await userApi.updateUser({
      id: userSet.value.id,
      name: userSet.value.name,
      age: userSet.value.age,
      gender: userSet.value.gender,
      address: userSet.value.address
    });
    if (response.data.code === 200) {
      ElMessage.success(response.data.message);
      updateDialog.value = false;
      getData();
      userSet.value = {
        id: null,
        name: '',
        age: null,
        gender: '男',
        address: ''
      };
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    console.error('无法更新用户:', error);
  }
};

const sizeChange = (val: number) => {
  size.value = val;
  if (searchuser.value.userName !== '') {
    search();
  } else {
    getData();
  }
};

const search = () => {
  if (searchuser.value.userName !== '') {
    getData();
  } else {
    ElMessage.error('搜索的用户名不能为空');
    getData();
  }
};

const currentChange = (val: number) => {
  current.value = val;
  if (searchuser.value.userName !== '') {
    search();
  } else {
    getData();
  }
};

const exportExcel = () => {
  window.open(userApi.exportExcel(searchuser.value.userName, current.value, size.value));
};
</script>

<style>
@import "@/assets/css/user.css";
</style>